define(["jquery", "ecp.utils", "ecp.utils.i18n", "ecp.component.attatchView"],function($, ecpUtils, localeJSON){
	"use strict";
	(function($){
		var isType = function(type){
			return function(obj){
				return {}.toString.call(obj) === "[object " + type +"]";
			}
		}
		var isObject = isType("Object");
		var isString = isType("String");
		var isUndefined = isType("Undefined");
		var isFunction = isType("Function");
		var isArray = Array.isArray || isType("Array");
		var panelHtml = {
			header : '<div class="bs_imgListTitle bs_subTitle djfj_title">' +
						'<div class="bs_imgListInfo">' +
							'<div class="subTitleIcon"></div>' +
							'<span>{title}</span>' +
							'<div class="subTitleArrow arrow_down" id=""></div>' +
						'</div>' +
					'</div>',
			main : '<div class="imageListbox" style="height: 191px;border:1px solid #c3d2e6;padding:8px;">' +
						'<ul style="height: 175px;width:100%;font-size: 10px;overflow: hidden;left: 0px;border:0px;" class="bs_imageListHor bs_imageListCont">' +
							'<div class="bs_addImgListBtn" style="width: 187px; height: 174px;display:{display}"></div>' +
							'<a class="bs_imgSildeLeft buttonLeft" id="prevFile"><span title="{previous}"value="{previous}"></span></a>' +
							'<a class="bs_imgSildeRight buttonRight" id="nextFile"><span title="{next}" value="{next}"></span></a>' +
							'<div style="width: 1488px;">' +
								'<ul id="container" style="left: 0px; ">{li}</ul>' +
							'</div>' +
						'</ul>' +
					'</div>' ,
			fileArea : '<li class="fileArea">' +
						'<div class="bgshow" style="border-radius: 4px;filter: alpha(opacity=8);opacity: 0.7;display:none;width: 186px;height: 173px;background-color: rgb(147, 147, 147);z-index: 1;position: absolute;margin-left: -9px;top: 0px;"></div>'+
						'<div style="width:100%;height: 15px;color: rgb(159, 155, 155);" class="fileNum">{num}/{count}</div><div style="width:170px; height:115px">' +
							'<div class="predow" style="display:none;width:170px;padding-top:60px;position:absolute;text-align:center;z-index: 2;"><span class="preview" style="cursor:pointer;margin-right:10px;background-color: #ffffff;"><i class="fa fa-eye" style="font-size:20px;"></i></span>'+
								'<span class="download" style="cursor:pointer;background-color: #ffffff;"><i class="fa fa-download" style="font-size:20px;"></i></span></div><image src="{src}" class="{image}" imgSrc="{imgSrc}" style="width:170px; height:115px" /></div>'+
							'<div class="text-center"><span title="{title}" style="width:167px">{fileName}</span><br/><span style="color: rgb(159, 155, 155);">{fileSizeText}：{fileSize}</span></div>' +
						'</li>' 
		};
		var locale = localeJSON.uploadPanel;
		var UploadPanel = function(element, options){
			this.$element = element;
			this.options = options;
			this.data = options.data;
			this.fileDatas = options.files;
			this.render(options);
			this.bindEvent();
		};
		UploadPanel.prototype = {
			constructor : UploadPanel,
			render : function(options){
				var _panel = panelHtml.main;
				var li = this.creatList(options.data);
				if(options.disabled === true){
					_panel = _panel.replace(/{display}/g, "none");
				}else{
					_panel = _panel.replace(/{display}/g, "");
				}
				if(options.showHeader){
					_panel = panelHtml.header + _panel;
				}
				_panel = _panel.replace(/{title}/g, options.title).replace(/{previous}/g, locale.previous).replace(/{next}/g, locale.next).replace(/{li}/g, li || '');
				this.$element.html(_panel);
				var $container = this.$container = $("#container", this.$element);
				this.children = $container.children();
				//默认
				$($container.children()[0]).addClass("activeFile"); 
				this.activeIndex = 0;
			},
			bindEvent : function(){
				var me = this;
				var $prev = $('#prevFile', me.$element);
				var $next = $('#nextFile', me.$element);
				var $add =  $('.bs_addImgListBtn', me.$element);
				var $arrow = $('.arrow_down', me.$element);
				var $listbox = $('.imageListbox', me.$element);
				//正常显示的文件总个数
				var showAccount = me.getShowList();
				$prev.off("click").on('click', function(){
					if(me.activeIndex === 0){
						if(me.data.length){
							ecpUtils.notify(locale.isFirst);
						}
						return ;
					}
					var $active = $(me.children[me.activeIndex]);
					if(me.getPrevs($active) === 0){
						//把前面一个节点显示出来
						$(me.children[me.activeIndex - 1]).fadeIn(100);
					}
					$active.removeClass("activeFile");
					me.activeIndex--;
					$(me.children[me.activeIndex]).addClass("activeFile");
				});
				$next.off("click").on('click', function(){
					var $active = $(me.children[me.activeIndex]);
					if(me.activeIndex === $active.siblings().length){
						if(me.data.length){
							ecpUtils.notify(locale.isLast);
						}
						return;
					}					
					//此时为正常显示的最后一个
					if(me.getPrevs($active) + 1 === me.getShowList()){
						//把最前面的隐藏
						$(me.children[me.activeIndex - showAccount + 1]).fadeOut(100);
					}
					$active.removeClass("activeFile");
					me.activeIndex++;
					$(me.children[me.activeIndex]).addClass("activeFile");
				});
				$add.off("click").on('click', function(){
					isFunction(me.options.uploadClick) && me.options.uploadClick();
				});
				$arrow.off("click").on('click', function(){
					$listbox[0].style.display === 'none' ? $listbox.show() : $listbox.hide();
				});
				//显示预览和下载按钮
				$(".fileArea", me.$element).off("mouseover").on("mouseover",function(e){
					var $me = $(this);
					if($me.find("img").hasClass("_image")){
						$me.find(".preview").hide();
					}
					$me.find(".bgshow").show();
					$me.find(".predow").show();
				}).off("mouseout").on("mouseout",function(e){
					$(this).find(".bgshow").hide();
					$(this).find(".predow").hide();
				}).off("click").on("click", "div>div>span", function(){
					
					var $me = $(this),
						nextObj = $me.parent().next(),
						url = nextObj.attr("src"),
						url = nextObj.attr("imgSrc") || url,
						opt = me.getFileData(url),
						options = opt.options,
						map = opt.map,
						ids = opt.ids,
						data = opt.data;
					//下载
					if($me.hasClass("download")){
						$("body").acpAttachment(options).fileDownload(data);
					}else if($me.hasClass("preview")){
						//预览
						$("body").acpAttachment(options).previewFile(data,map,ids);
					}
				})
			},
			getFileData : function(url){
				var me = this,
					urlObj = ecpUtils.getAllArgument(url),
					fileDatas = me.fileDatas,
					ids = [],
					map = {},
					files = [];
				for(var i=0,j=fileDatas.length; i<j; i++){
					var d = fileDatas[i];
					var resId = d.resId;
					var title = d.title;
					var file = {
						 fileLength: ( d.bsize/1024 ) + "",
						 fileName: title,
						 fileType: d.btype,
						 gid: resId,
						 previewUrl: "/grm/gris/contentmanage.viewFileServlet?resId="+resId,
						 smallPicUrl: ""
					}
					files.push(file);
					map[resId] = file;
					ids.push(resId);
				}
				var options = {
					data : files,
					loginContext: {compId: urlObj.orgCode, userId:urlObj.userCode}
				}
				var data = map[urlObj.resId];
				return {
					options : options,
					map : map,
					ids : ids,
					data : data
				};
			},
			creatList : function(data){
				if(isArray(data) && data.length){
//					data = data[0];
					this.fileDatas = data;
					var defaultIcon = "/grm/ecp/webcore/themes/default/upload/images/",
						_html = "",
						length = data.length,
						i = 0;
					for(; i < length; i++){
						var item = data[i];
						var fileType = item.fileType;
						if(!fileType){return;}
						fileType = fileType.toLocaleLowerCase();
						if(this.isImage(fileType)){
							_html += panelHtml.fileArea.replace(/{num}/g, i+1).replace(/{count}/g, length).replace(/{src}/g, item.url).replace(/{title}/, item.fileName).replace(/{fileName}/g, this.cutStr(item.fileName, fileType))
														.replace(/{fileSizeText}/g, locale.fileSize).replace(/{fileSize}/g, this.getSize(item.fileSize)).replace(/{image}/g,"").replace(/{imgSrc}/g,"");
						}else{
							var defaultsSrc = defaultIcon + fileType + '.png';
							_html += panelHtml.fileArea.replace(/{num}/g, i+1).replace(/{count}/g, length).replace(/{src}/g, defaultsSrc).replace(/{title}/, item.fileName).replace(/{fileName}/g, this.cutStr(item.fileName, fileType))
														.replace(/{fileSizeText}/g, locale.fileSize).replace(/{fileSize}/g, this.getSize(item.fileSize)).replace(/{image}/g,"_image").replace(/{imgSrc}/g,item.url);
						}
					}
					return _html;
				}
			},
			getSize : function(fileSize){
				if(!fileSize){return "0 KB";}
				var res; 
				if(fileSize < 524288){
					res = (parseFloat(fileSize,10)/1024).toFixed(2) + " KB";
				}else{
					res = (parseFloat(fileSize,10)/1048576).toFixed(2)+ " MB";
				}
				return res;
			},
			getPrevs : function(element){
				var prevAll = element.prevAll();
				var count = 0;
				$.each(prevAll, function(index, ele){
					if(ele.style.display !== 'none'){
						count++;
					}
				});
				return count;
			},
			getShowList : function(){
				return Math.floor(this.$element.width()/195 - 1);
			},
			getFileType : function(src){
				if(isString(src)){
					var fileType = src.substring(src.lastIndexOf(".")+ 1,src.length);
					fileType = fileType.toLowerCase();
					return fileType;
				}
			},
			isImage : function(fileType){
				if(isString(fileType)){
					fileType = fileType.toLocaleLowerCase();
					var fileList = ["jpg", "jpeg", "bmp", "gif", "png", "tif"];
					return fileList.some(function(item){
						return fileType === item;
					});
				}
			},
			cutStr : function(str, fileType){
				str = str +"." + fileType;
				if(isString(str)){
					if(str.len() > 28){
						str = str.subStringForChinese(0,25) + '...';
					} 
					return str;
				}
			},
			val : function(value){
				if(isUndefined(value)){
					return this.data;
				}else{
					var _html = this.creatList(value);
					this.$container.append(_html);
					for(var i=0,j=value.length;i<j;i++){
						this.data.push(value[i]);
					}
					this.children = this.$container.children();
					this.bindEvent();
				}
			},
			destroy : function(){
				//销毁
				this.$container.children().remove();
				this.activeIndex = 0;
				this.data = [];
				this.children = [];
			},
			disable : function(){
				this.$element.find(".bs_addImgListBtn").hide();
			},
			enable : function(){
				this.$element.find(".bs_addImgListBtn").show();
			}
		};
		var old = $.fn.uploadPanel;
		$.fn.uploadPanel = function(option){
			var me = this;
			option = option || {};
			var type = typeof(option);
			//如果第一个参数传入的是对象或空则初始化空件，如果传入的是字符串，则认为是调用里面的内部方法。
			if (type === "object") {
				var eus = [];
				this.each(function() {
					var instanceOption = $.extend({}, option, true);
					var instance = new UploadPanel($(this), instanceOption);
					this.uploadPanel = instance;
					eus.push(instance);
				});
				if(eus.length === 1){
					eus = eus[0];
				}
				return eus;
			} else if (type === "string") {
				var args = Array.prototype.slice.call(arguments, 1);
				this.each(function() {
					if(!this.uploadPanel){
						this.uploadPanel = new UploadPanel($(this), args[0]);
					}
					if($.isFunction(this.uploadPanel[option])){
						this.uploadPanel[option].call(this.uploadPanel,args[0]);
					}
				})
			} else if (option === true) {
				return me[0] && me[0].simpleUploader;
			}
		};
		$.fn.uploadPanel.Constructor = UploadPanel;
		$.fn.uploadPanel.noConflict = function() {
			$.fn.uploadPanel = old;
			return this;
		};
		$.fn.uploadPanel.defaults = {
			showHeader : true,
			title : locale.attachName, 
			uploadClick : function(){}, //点击上传事件
			data : [],
			disabled : false
		};
	}(jQuery));
});
	
